<?php
if (!defined("YUEXUAN_REAL_ROOT_PATH")) {
    exit("Access Denied.");
}

include_once(dirname(__FILE__)."/../ext/phpQuery/phpQuery.php");

class importException extends Exception
{
    // pass
}

/**
 * 导入数据
 * @author tongjun
 *
 */
class tally_import extends base
{
    private $userId = null;
    private $loginUrl = 'http://www.caakee.com/login.do';
    private $zxUrl = 'http://zx.caakee.com';

    public function __construct($userId)
    {
        $this->userId = $userId;
    }

    public function login($loginAccount, $loginPassword)
    {
        $cookie = "";
        $location = "";
        fetchUrl(
            $this->loginUrl,
            array(
                'loginName' => $loginAccount,
                'password' => $loginPassword
            ), $cookie, $location
        );
//        echo $location;exit;
        if($location){
            $cookie = "";
            fetchUrl1(trim($location), $cookie, $location);
        }else{
            throw new importException("登录失败, location 1 is empty");
        }
        if($location){
            fetchUrl1(trim($location), $cookie, $location);
        }else{
            throw new importException("登录失败, location 2 is empty");
        }
        if(!$cookie){
            throw new importException("登录失败, cookie is empty");
        }
        $_SESSION['import'] = array(
            'cookie' => $cookie
        );
    }

    private function queryAccountList()
    {
        $body = fetchUrl($this->zxUrl . '/setting/account.do?method=listQry&showInvisible=1&randomid=7606_1466473006405',
            array(), $_SESSION['import']['cookie']
        );

        $accountClass = new tally_account();
        $flowClass = new tally_flow();
//        var_dump($_SESSION['import']['cookie']);
//        var_dump($body);
        $accountList = array();
        $accountList_hide = array();
        phpQuery::newDocumentHTML($body);
        $items = pq('#listtb tbody tr');
        foreach($items as $item){
            $item = pq($item);

            $id = $item->find("td input")
                ->attr("value");
            $id = intval($id);

            $name = $item->find("td")
                ->filter(':eq(1)')
                ->text();
            $name = trim($name);

            $type = $item->find("td")
                ->filter(':eq(2)')
                ->text();
            $type = trim($type);

            $initVal = $item->find("td")
                ->filter(':eq(3)')
                ->text();
            $initVal = floatval(str_replace(array(',', ' '), '',trim($initVal)));

            $remain = $item->find("td")
                ->filter(':eq(4)')
                ->text();
            $remain = floatval(str_replace(array(',', ' '), '',trim($remain)));

            $isShow = false;
            $orderIndex = $item->find("td")
                ->filter(':eq(7)')
                ->find('input');
            if(count($orderIndex)){
                $isShow = true;
                $orderIndex = $orderIndex->attr('value');
            }
            $remain = floatval(str_replace(array(',', ' '), '',trim($remain)));

            $accountInfo = array(
                "id" => $id,
                "name" => $name,
                "remain" => $remain,
                "type" => $type
            );

            if($isShow){
                $accountList[] = $accountInfo;
            }else{
                $accountList_hide[] = $accountInfo;
            }
            $accountClass->findOrCreateAccountId($this->userId, $name, $orderIndex, $isShow);
        }
        return array_merge($accountList, $accountList_hide);
    }

    public function importStart()
    {
        $accountList = $this->queryAccountList();
//        print_r($accountList);

        $_SESSION['import']['accountList'] = $accountList;
        $_SESSION['import']['totalAccountCount'] = count($accountList);

        $_SESSION['import']['currentAccountInTotal'] = 0;
        $_SESSION['import']['pageCount'] = null;
        $_SESSION['import']['page'] = null;
    }

    public function getStatus()
    {
        return $_SESSION['import'];
    }

    public function importFlows()
    {
        if($_SESSION['import']['pageCount']!==null){
            if($_SESSION['import']['page']!==null){
                $page = --$_SESSION['import']['page'];
            }else{
                $page = $_SESSION['import']['page'] = $_SESSION['import']['pageCount'];
            }

            if($page<1){
                $_SESSION['import']['currentAccountInTotal']++;
                $_SESSION['import']['pageCount'] = null;
                $_SESSION['import']['page'] = null;
                return ;
            }
        }else{
            $page = 1;
        }

        $accountInfo = $_SESSION['import']['accountList'][$_SESSION['import']['currentAccountInTotal']];
        $body = $this->cashListQry($accountInfo["id"], $page);

        $flowClass = new tally_flow();
        $accountClass = new tally_account();
        $tagClass = new tally_tag();
        $flowTypeClass = new tally_flowType();

        phpQuery::newDocumentHTML($body);
        if($_SESSION['import']['pageCount']===null){
            $pageBar = pq('.pagebar');
            preg_match_all('/共\s*(\d+)\s*页/', $pageBar->text(), $a);
            $totalPage = intval(trim($a[1][0]));
            $_SESSION['import']['pageCount'] = $totalPage;
            $_SESSION['import']['page'] = null;
        }

        $items = pq('.list_line');
        $flowList = array();
        foreach($items as $item)
        {
            $item = pq($item);
            $time = $item->find("td")
                ->filter(':first')
                ->find("p")[0]->attr("title");
//            var_dump($time);

            $direct = $item->find("td")
                ->filter(':eq(1)')
                ->find("span img");

            $tmp = $item->find("td")
                ->filter(':eq(1)')
                ->find("span")[0]->text();
//            var_dump($tmp);
            $a = explode(" ", trim($tmp));
//            var_dump($a);
            $flowType = "";
            if(count($direct)>0){
                $flowType = trim($a[count($a)-1]);
            }
            $a1 = explode("|", trim($a[0]));
            $inout = "";
            if(count($a1)>1){
                $inout = trim($a1[0]);
            }
            $account = trim($a1[count($a1)-1]);
//            var_dump($flowType);
//            var_dump($inout);
//            var_dump($account);

            $direct = $item->find("td")
                ->filter(':eq(1)')
                ->find("span img")[0]->attr("src");
            $direct = $direct==="/images/flow_right.gif"?"right":"left";

            $moneyIn = $item->find("td")
                ->filter(':eq(3)')
                ->text();
            $moneyIn = floatval(str_replace(array(',', ' '), '',trim($moneyIn)));
            $moneyOut = $item->find("td")
                ->filter(':eq(4)')
                ->text();
            $moneyOut = floatval(str_replace(array(',', ' '), '',trim($moneyOut)));
//            var_dump($moneyIn);
//            var_dump($moneyOut);

            $accountInfo = array();
            foreach ($_SESSION['import']['accountList'] as $t){
                if($t['name']===$account){
                    $accountInfo = $t;
                    break;
                }
            }

            if($accountInfo['type']==='信用卡'){
                $t = $moneyIn;
                $moneyIn = $moneyOut;
                $moneyOut = $t;
            }

            $remain = $item->find("td")
                ->filter(':eq(5)')
                ->text();
            $remain = floatval(str_replace(array(',', ' '), '',trim($remain)));

            $desc = $item->find("td")
                ->filter(':eq(6)')
                ->text();
//            $desc = '
//
//					    		[零食,买菜]
//
//					    	lmc
//
//							';
//            $desc = '
//
//					    		[充话费]
//
//							';
//            $desc = '
//
//
//					    	lmc
//
//							';
            $desc = trim($desc);

//            echo '<br><br>';
//            var_dump($desc);
            preg_match_all('/^(\[.*?\])?\s*([\s\S]+)?\s*$/', $desc, $a);
//            var_dump($a);
//            exit();
            $tags = trim($a[1][0]);
            $tags = str_replace(array('[',']'), '', $tags);
            if($tags){
                $tags = explode(",", $tags);
            }else{
                $tags = [];
            }
//            var_dump($tags);
            $desc = trim($a[2][0]);
//            var_dump($desc);

            $id = $item->find(".oper_bar .deleteBtn")->attr("onclick");
//            var_dump($id);
            preg_match_all('/Tally\.onDelete\(\'(\d+)\'\)/', $id, $a);
//            var_dump($a);
            $id = intval($a[1][0]);
//            var_dump($id);
//            exit();

            $accountId = $accountClass->findOrCreateAccountId($this->userId, $account);
            if(!$inout){
                if($accountClass->findAccountByName($this->userId, $flowType)){
                    $inout = "转账";
                }else if($moneyIn>0){
                    $inout = "收入";
                }else if($moneyOut>0){
                    $inout = "支出";
                }
            }
            switch ($inout){
                case "收入":
                case "期初余额":
                case "卖出基金":
                case "卖出股票":
                    if($inout!=='收入'){
                        $desc += $inout;
                    }
                    $inout = tally_flow::$INOUT_INCOMME;
                    $subjectId1 = $flowTypeClass->findOrCreateFlowTypeId($this->userId, $flowType, $inout);
                    break;
                case "支出":
                case "买入基金":
                case "买入股票":
                    if($inout!=='支出'){
                        $desc += $inout;
                    }
                    $inout = tally_flow::$INOUT_EXPENSE;
                    $subjectId1 = $flowTypeClass->findOrCreateFlowTypeId($this->userId, $flowType, $inout);
                    break;
                case "转账":
                case "还信用卡":
                    if($inout!=='转账'){
                        $desc += $inout;
                    }
                    $inout = tally_flow::$INOUT_TRANSFER;
                    if($moneyOut>0){
                        $subjectId1 = $accountClass->findOrCreateAccountId($this->userId, $flowType);
                    }else{
                        $subjectId1 = $accountId;
                        $accountId = $accountClass->findOrCreateAccountId($this->userId, $flowType);
                        $t = $moneyIn;
                        $moneyIn = $moneyOut;
                        $moneyOut = $t;
                    }
                    break;
                default:
                    var_dump($inout);
                    echo $inout.$page;
                    exit();
                    break;
            }

            $tagIds = array();
            if(count($tags)){
                foreach($tags as $tag){
                    $tagIds[] = $tagClass->findOrCreateTagId($this->userId, $tag);
                }
            }

            if($inout===tally_flow::$INOUT_TRANSFER && !$subjectId1){
                var_dump($page);
                var_dump($id);
                var_dump($item);
                exit();
            }
//            var_dump($id);
//            var_dump($money);
//            echo '<br>';
            //var_dump($item);
//            echo '<br>';

            array_unshift($flowList, array(
                "accountId"=>$accountId,
                "time"=>$time,
                "inout"=>$inout,
                "subjectId1"=>$subjectId1,
                "moneyIn"=>$moneyIn,
                "moneyOut"=>$moneyOut,
                "tagIds"=>$tagIds,
                "desc"=>$desc,
                "id"=>$id,
            ));
        }

        foreach ($flowList as $flowItem){
            $flowClass->createFlow($this->userId, $flowItem["accountId"],$flowItem["time"],$flowItem["inout"],
                $flowItem["subjectId1"],$flowItem["moneyIn"],$flowItem["moneyOut"],$flowItem["tagIds"],
                $flowItem["desc"],$flowItem["id"]);
        }
//        exit();
    }

    private function cashListQry($subjectId, $page)
    {
        $useCache = true;
        $cachePath = YUEXUAN_REAL_ROOT_PATH."/tmp/" .$subjectId."-". $page . ".html";
        if($useCache && file_exists($cachePath)){
            return file_get_contents($cachePath);
        }
        $body = fetchUrl($this->zxUrl.'/tally/cash!listQry.do?&curPage='.$page,
            'dateSpan=&dateFrom=&dateTo=&orderField=vc.trade_time+desc%2Cvc.voucher_id+desc&categoryId=&categoryName=&payeeId=&tagName=&remark=&subjectId='.$subjectId,
            $_SESSION['import']['cookie']
        );

        $useCache && file_put_contents($cachePath, $body);

        return $body;
    }
}

